package com.andnnl.template.param;

import com.fasterxml.jackson.databind.JsonNode;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 长整数类型参数配置
 */
public class LongParamConfig extends NumericParamConfig<Long> {
    @Override
    public void validate() {
        if (minValue != null && maxValue != null && maxValue > 0 && minValue > maxValue)
            throw new IllegalArgumentException("数值范围无效: " + name + "，minValue=" + minValue + "，maxValue=" + maxValue);
    }

    @Override
    public String generateValue() {
        Long min = (minValue != null) ? minValue : 0L;
        Long max = (maxValue != null) ? maxValue : 100L;
        return String.valueOf(RandomUtil.randomLong(min, max));
    }

    @Override
    public void fromJson(JsonNode node) {
        if (node.has("minValue") && !node.get("minValue").isNull()) {
            setMinValue(node.get("minValue").asLong());
        }
        if (node.has("maxValue") && !node.get("maxValue").isNull()) {
            setMaxValue(node.get("maxValue").asLong());
        }
    }

    @Override
    public boolean validateValue(String value) throws IllegalArgumentException {
        if (StrUtil.isBlank(value)) {
            throw new IllegalArgumentException("长整数参数" + name + "不能为空");
        }
        try {
            long longValue = Long.parseLong(value);
            if (minValue != null && longValue < minValue) {
                throw new IllegalArgumentException("长整数参数" + name + "必须大于等于" + minValue + "，实际值：" + longValue);
            }
            if (maxValue != null && longValue > maxValue) {
                throw new IllegalArgumentException("长整数参数" + name + "必须小于等于" + maxValue + "，实际值：" + longValue);
            }
            return true;
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("参数" + name + "不是有效的长整数: " + value, e);
        }
    }
}